package com.learn.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect
@Order(1)   // 切面优先级设为最高
@Profile("dev")
public class DevServiceFuncLogAOP {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    // 切点范围(监控Service注解)
    @Pointcut("execution(* com..*(..)) && @target(org.springframework.stereotype.Service)")
    public void pointcut() {}

    @Around(value = "pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object result;
        long time1 = System.currentTimeMillis();
        try {
            result = pjp.proceed();
        } catch (Throwable throwable) {
            logger.error("\n\n============================================\n"
            + "===errFunc:" + pjp.getSignature()
            + "\n===params:" + Arrays.toString(pjp.getArgs())
            + "\n============================================\n");
            throw throwable;
        }
        long time2 = System.currentTimeMillis();
        logger.info("\n\n============================================\n"
        + "===func:" + pjp.getSignature()
        + "\n===params:" + Arrays.toString(pjp.getArgs())
        + "\n===time:" + (time2-time1) + "ms"
        + "\n===result:" + result
        + "\n============================================\n");
        return result;
    }
}
